package cn.myapps.demospringsecurity.controller;

import cn.myapps.demospringsecurity.utils.JwtUtil;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    // 注入 CustomAuthenticationManager
    @Autowired
    private AuthenticationManager authenticationManager;
    /**
     * 密钥长度
     */
    private static final int KEY_SIZE = 2048;
    /**
     * 公钥密钥
     */
    private KeyPair keyPair;

    /**
     * 初始化公钥密钥
     */
    @PostConstruct
    public void init() throws NoSuchAlgorithmException {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(KEY_SIZE); // 建议2048位及以上
        this.keyPair = generator.generateKeyPair();
    }

    // 获取公钥接口（PEM格式）
    @GetMapping("/public-key")
    public String getPublicKey() {
        PublicKey publicKey = keyPair.getPublic();
        return Base64.getEncoder().encodeToString(publicKey.getEncoded())
                .replace("\n", "")
                .replace("\r", "");
    }

    /**
     * 解密接口
     */
    @PostMapping("/doLogin")
    public ResponseEntity<?> login(@RequestBody Map<String,String> request) {
        // 提取 username 和 password
        String username = request.get("username");
        String password = request.get("password");

        // 验证 Base64 合法性
        if (isValidBase64(username) || isValidBase64(password)) {
            return ResponseEntity.badRequest().body("参数包含非法字符");
        }

        try {
            // 解码 Base64
            byte[] usernameBytes = Base64.getDecoder().decode(username);
            byte[] passwordBytes = Base64.getDecoder().decode(password);

            // 使用私钥解密（确保密钥匹配）
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

            byte[] decryptedUsername = cipher.doFinal(usernameBytes);
            byte[] decryptedPassword = cipher.doFinal(passwordBytes);
            username = new String(decryptedUsername);
            password = new String(decryptedPassword);
            // 使用 CustomAuthenticationManager 进行认证
            try {
                Authentication authentication = authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(username, password)
                );
                if (authentication.isAuthenticated()) {
                    String token = JwtUtil.genAccessToken(username);
                    Map<String, String> response = new HashMap<>();
                    response.put("token", token);
                    return ResponseEntity.ok(response);
                }
            } catch (AuthenticationException e) {
                return ResponseEntity.status(401).body("账号名或密码错误");
            }
            // return ResponseEntity.ok(
            //         "Username: " + new String(decryptedUsername) +
            //                 ", Password: " + new String(decryptedPassword)
            // );
        } catch (Exception e) {
            return ResponseEntity.status(500).body("解密失败: " + e.getMessage());
        }
        return ResponseEntity.status(401).body("账号名或密码错误");
    }

    // 辅助方法：验证 Base64 合法性
    private boolean isValidBase64(String data) {
        return data == null ||
                !data.matches("^[A-Za-z0-9+/=]*$") ||
                data.length() % 4 != 0;
    }
}
